package com.tywj.buscustomerapp.view.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tywj.buscustomerapp.Config;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.BaseReqeust;
import com.tywj.buscustomerapp.model.bean.BusTravelBean;
import com.tywj.buscustomerapp.model.bean.DateJoe;
import com.tywj.buscustomerapp.model.bean.DaysNew;
import com.tywj.buscustomerapp.model.bean.PayResult;
import com.tywj.buscustomerapp.model.bean.PayResuolt;
import com.tywj.buscustomerapp.model.bean.RequesrDaysTicketBean;
import com.tywj.buscustomerapp.model.bean.RequestBean;
import com.tywj.buscustomerapp.model.bean.TravelLineBean;
import com.tywj.buscustomerapp.model.bean.WPayRequest;
import com.tywj.buscustomerapp.utils.PhoneUtils;
import com.tywj.buscustomerapp.utils.TaylorClickLinstener;
import com.tywj.buscustomerapp.utils.TimeRender;
import com.tywj.buscustomerapp.utils.ToastUtils;
import com.tywj.buscustomerapp.view.myview.LoadingDialog;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

public class PayActivity extends BaseActivity {
    @BindView(R.id.head_left) ImageView back;
    @BindView(R.id.head_title) TextView title;
    @BindView(R.id.submit) TextView submit;
    @BindView(R.id.line_name) TextView line_name;
    @BindView(R.id.start) TextView startL;
    @BindView(R.id.end) TextView endL;
    @BindView(R.id.line_date) TextView line_data;
    @BindView(R.id.ticket_num) TextView ticket_num;
    @BindView(R.id.ticket_price) TextView ticket_price;
    @BindView(R.id.pay_group)
    RadioGroup radioGroup;
    @BindView(R.id.pay_time) TextView paytime;
    @BindView(R.id.buy_info) TextView buyinfo;

    private int pos = 0;
    private List<DaysNew.DataBean> checkTickets=new ArrayList<>();
    private BusTravelBean.DataBean.ResultListBean travelLineBean;
    private String start;
    private String end;
    private String price;
    private RequestBean requestBean;
    private boolean isAliPay = true;
    private final int SDK_PAY_FLAG =1010;
    private int  recLen = 180;
    private Timer timer;
    private TimerTask task;
    private AlertDialog build;
    private IWXAPI api;
    private PayReq req;
    private RequesrDaysTicketBean requesrDaysTicketBean;
    public static PayActivity activity;
    private int number = 1;
    @Override
    protected int getContentId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        title.setText("支付");
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Config.WXCODE);
        activity = this;
        if (getIntent()!=null){
            pos = getIntent().getIntExtra("position",0);
            if (pos==0) {
                travelLineBean = (BusTravelBean.DataBean.ResultListBean) getIntent().getSerializableExtra("bean");
                checkTickets = (List<DaysNew.DataBean>) getIntent().getSerializableExtra("list");
                start = getIntent().getStringExtra("start");
                end = getIntent().getStringExtra("end");
                price = getIntent().getStringExtra("price");
                requestBean = (RequestBean) getIntent().getSerializableExtra("pay");
                number = getIntent().getIntExtra("number",1);
            }else if (pos==1){
                requesrDaysTicketBean = (RequesrDaysTicketBean) getIntent().getSerializableExtra("bean");
            }
        }
        if (checkTickets!=null && checkTickets.size()>0) {
            line_name.setText(travelLineBean.getXlqsz() + "——" + travelLineBean.getXlzdz());
            startL.setText(start);
            endL.setText(end);
            String data = checkTickets.get(0).getRiqi();
            for (int i = 1; i < checkTickets.size(); i++) {
                data = data + "," + checkTickets.get(i).getRiqi();
            }
            line_data.setText(data);
            ticket_num.setText((checkTickets.size()*number) + "张");
            ticket_price.setText("￥" + requestBean.getData().getTotalFee());
            submit.setText("确认支付￥" + requestBean.getData().getTotalFee());
        }else{
//            if (requesrDaysTicketBean!=null){
//                price = requesrDaysTicketBean.getData().getTotalFee();
//                line_name.setText(requesrDaysTicketBean.getData().getBody());
//                startL.setText("");
//                endL.setText("");
//                line_data.setText("订单日期:"+requesrDaysTicketBean.getData().getCreateDate());
//                ticket_num.setText(1 + "张");
//                ticket_price.setText("￥" + price);
//                submit.setText("确认支付￥" + price);
//            }
            line_name.setText(travelLineBean.getXlmc()+"月票");
            startL.setText(start);
            endL.setText(end);
            line_data.setText(TimeRender.getMonth()+"月");
            ticket_num.setText(1 + "张");
            ticket_price.setText("￥" + requestBean.getData().getTotalFee());
            submit.setText("确认支付￥" + requestBean.getData().getTotalFee());
        }
        radioGroup.check(R.id.alipay);
        startTime();
    }

    @Override
    protected void initClick() {
        super.initClick();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog("取消购票","确定取消购票吗？");
            }
        });

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.alipay:
                        isAliPay = true;
                        break;
                    case R.id.wecharpay:
                        isAliPay = false;
                        break;
                }
            }
        });

        submit.setOnClickListener(new TaylorClickLinstener() {
            @Override
            public void onMultiClick(View v) {
                if (isAliPay){
                    doAliPay();
                }else{
                    doWXPay();
                }
            }
        });

        buyinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PayActivity.this,InfoActivity.class);
                intent.putExtra("type",1);
                startActivity(intent);
            }
        });

    }

    public void doWXPay(){
        req = new PayReq();
//        Log.i("taylor",PhoneUtils.getIPAddress(PayActivity.this));
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //创建一个请求
        String url = Config.SBURL + "/order/toPay";
        JSONObject object = new JSONObject();
        try {
            object.put("orderType","weixin");
            object.put("realIp", PhoneUtils.getIPAddress(PayActivity.this));
            if (pos==1){
                object.put("id",requesrDaysTicketBean.getData().getId());
            }else{
                object.put("id",requestBean.getData().getId());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.i("taylor",String.valueOf(jsonObject));
                final WPayRequest data = new Gson().fromJson(String.valueOf(jsonObject),WPayRequest.class);
                if (data!=null){
                    if (data.getReCode().equals("201")){
                        req.appId = Config.WXCODE;
                        req.partnerId = data.getData().getPartnerId();
                        req.prepayId = data.getData().getPrepayid();
                        req.nonceStr = data.getData().getNoncestr();
                        req.timeStamp = data.getData().getTimestamp();
                        req.packageValue = data.getData().getPackageX();
                        req.sign = data.getData().getSign();
                        req.transaction = pos+"";
                        api.sendReq(req);
                    }else{
                        Toast.makeText(PayActivity.this, data.getCodeTxt(), Toast.LENGTH_SHORT).show();
                    }
                }else{
                    ToastJoe.getmToastJoe().ToastLongShow(PayActivity.this,null,"支付失败，请重新支付");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastJoe.getmToastJoe().ToastLongShow(PayActivity.this,null,"支付失败，请重新支付");
            }
        });
        //将创建的请求添加到队列中
        requestQueue.add(jsonObjectRequest);
    }




    public void doAliPay(){
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //创建一个请求
        String url = Config.SBURL + "/order/toPay";
        JSONObject object = new JSONObject();
        try {
            object.put("orderType","zfb");
            if (pos==1){
                object.put("id",requesrDaysTicketBean.getData().getId());
            }else{
                object.put("id",requestBean.getData().getId());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.i("taylor",String.valueOf(jsonObject));
                final PayResuolt data = new Gson().fromJson(String.valueOf(jsonObject),PayResuolt.class);
                if (data!=null){
                    if (data.getReCode().equals("201")){
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(PayActivity.this);
                                Map<String, String> result = alipay.payV2(data.getData().getUrl(),true);
                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }else if (data.getReCode().equals("202")){
                        ToastJoe.getmToastJoe().ToastShowRight(getApplicationContext(),null,"支付成功");
                        Intent intent = new Intent(PayActivity.this, MyTicketActivity.class);
                        startActivity(intent);
                        newBuyTicketActivity.activity.finish();
                        finish();
                    }else{
                        Toast.makeText(PayActivity.this, data.getCodeTxt(), Toast.LENGTH_SHORT).show();
                    }
                }else{
                    ToastJoe.getmToastJoe().ToastLongShow(PayActivity.this,null,"支付失败，请重新支付");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastJoe.getmToastJoe().ToastLongShow(PayActivity.this,null,"支付失败，请重新支付");
            }
        });
        //将创建的请求添加到队列中
        requestQueue.add(jsonObjectRequest);
    }

    private IWXAPIEventHandler wxHandler = new IWXAPIEventHandler() {

        @Override
        public void onReq(BaseReq baseReq) {

        }

        @Override
        public void onResp(BaseResp baseResp) {
            if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
                AlertDialog.Builder builder = new AlertDialog.Builder(PayActivity.this);
                builder.setTitle("支付结果");
                builder.setMessage(getString(R.string.pay_result_callback_msg, String.valueOf(baseResp.errCode)));
                builder.show();
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            showDialog("取消购票","确定取消购票吗？");
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastJoe.getmToastJoe().ToastShowRight(PayActivity.this,null,"支付成功");
                        if (pos==0) {
                            if (checkTickets!=null && checkTickets.size()>0){
                                Intent intent = new Intent(PayActivity.this, MyTicketActivity.class);
                                startActivity(intent);
                                newBuyTicketActivity.activity.finish();
                            }else{
                                Intent intent = new Intent(PayActivity.this, MyMonthTicketActivity.class);
                                startActivity(intent);
                                newBuyTicketActivity.activity.finish();
                            }

                            finish();
                        }else if (pos==1){
                            // TODO: 2018/7/3 做跳转
                            finish();
                        }
//                        intent.putExtra("position",pos);

                    } else {
                        ToastJoe.getmToastJoe().ToastLongShow(PayActivity.this,null,"支付失败，请重新支付");
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    private void showDialog(final String title, final String msg){
        build = new AlertDialog.Builder(PayActivity.this,R.style.AlertDialogStyle).create();
        //自定义布局
        View view = getLayoutInflater().inflate(R.layout.dialog_nopay_layout, null);
        build.setView(view, 0, 0, 0, 0);
        build.show();
        //得到当前显示设备的宽度，单位是像素
        int width = getWindowManager().getDefaultDisplay().getWidth();
        //得到这个dialog界面的参数对象
        WindowManager.LayoutParams params = build.getWindow().getAttributes();
        //设置dialog的界面宽度
        params.width = width-(width/3);
        //设置dialog高度为包裹内容
        params.height =  WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的重心
        params.gravity = Gravity.CENTER;
        build.getWindow().setAttributes(params);
        build.setCanceledOnTouchOutside(false);
        build.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {

            }
        });
        TextView titleTv = view.findViewById(R.id.message);
        TextView messageTv = view.findViewById(R.id.message1);
        titleTv.setText(title);
        messageTv.setText(msg);
        Button btn_sure = view.findViewById(R.id.yes);
        Button btn_cancel = view.findViewById(R.id.no);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                build.dismiss();
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                build.dismiss();
                if (requesrDaysTicketBean==null) {
//                    doCancleTicket(requestBean.getData().getId() + "");
//                    showLoading();
                    finish();
                }else{
                    finish();
                }
            }
        });
    }


    private void doCancleTicket(String id){
        //创建一个请求队列
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //创建一个请求
        String url = Config.SBURL + "/order/cancelNopayOrder";
        JSONObject object = new JSONObject();
        try {
            object.put("orderId",id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.i("taylor",String.valueOf(jsonObject));
                BaseReqeust data = new Gson().fromJson(String.valueOf(jsonObject),BaseReqeust.class);
                closeLoading();
                finish();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                finish();
            }
        });
        //将创建的请求添加到队列中
        requestQueue.add(jsonObjectRequest);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer!=null){
            timer.cancel();
        }
        if (build!=null && build.isShowing()) {
            build.dismiss();
        }
    }

    private void startTime() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {      // UI thread
                    @Override
                    public void run() {
                        try{
                            recLen--;
                            int min = recLen/60;
                            int s = recLen%60;
                            if (s<10){
                                paytime.setText("支付倒计时 0"+min+":0"+s);
                            }else{
                                paytime.setText("支付倒计时 0"+min+":"+s);
                            }
                            if(recLen < 1){
                                timer.cancel();
                                ToastUtils.show("支付超时，请重新下单");
                                finish();
//                                showDialog("支付超时","支付超时，请重新下单");
                            }
                        }catch (Exception e){
//                            showDialog("支付超时","支付超时，请重新下单");
                            finish();
                        }
                    }
                });
            }
        };
        timer.schedule(task, 1000, 1000);
    }

    private LoadingDialog waitDialog;
    public void showLoading() {
        if (waitDialog==null)
            waitDialog = new LoadingDialog(PayActivity.this);
        if (!waitDialog.isShowing())
            waitDialog.show();
    }

    public void closeLoading() {
        if (waitDialog!=null && waitDialog.isShowing())
            waitDialog.dismiss();
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("支付");
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("支付");
        MobclickAgent.onPause(this);
    }

}
